import { Body, Inject, Post } from '@midwayjs/core';
import {
  CoolController,
  BaseController,
  CoolTag,
  TagTypes,
} from '@cool-midway/core';
import { DeviceDeviceEntity } from '../../entity/device';
import { DeviceDeviceService } from '../../service/device';
import { UserInfoEntity } from '../../../user/entity/info';

/**
 * 设备信息
 */
@CoolController({
  api: ['delete', 'info', 'list', 'page'],
  entity: DeviceDeviceEntity,
  service: DeviceDeviceService,
  pageQueryOp: {
    keyWordLikeFields: ['a.deviceNo'],
    fieldEq: ['a.deviceStatus', 'a.userId', 'a.agentId'],
    // 4.x新增
    join: [
      {
        entity: UserInfoEntity,
        alias: 'b',
        condition: 'a.userId = b.id',
        type: 'leftJoin',
      },
      {
        entity: UserInfoEntity,
        alias: 'c',
        condition: 'a.agentId = c.id',
        type: 'leftJoin',
      },
    ],
    select: [
      'a.*',
      'b.phone AS deviceBindPhone',
      'b.nickName AS deviceBindNickName',
      'c.phone AS agentPhone',
      'c.nickName AS agentNickName',
    ],
  },
})
export class AdminDeviceDeviceController extends BaseController {
  @Inject()
  deviceDeviceService: DeviceDeviceService;

  // 自定义接口
  // 获取设备二维码
  @Post('/getQrCode')
  async getQrCode(@Body() params) {
    return this.ok(await this.deviceDeviceService.getDeviceQrCode(params));
  }

  // 添加设备
  @Post('/add')
  async addDevice(@Body() params) {
    return this.ok(await this.deviceDeviceService.add(params));
  }

  // 不需要登陆
  @CoolTag(TagTypes.IGNORE_TOKEN)
  // 批量新增
  @Post('/addBatch')
  async addDeviceBatch(@Body() params) {
    return this.ok(await this.deviceDeviceService.addBatch(params));
  }

  // 编辑设备
  @Post('/update')
  async editDevice(@Body() params) {
    return this.ok(
      await this.deviceDeviceService.update({
        id: params.id,
        deviceNo: params.deviceNo,
        deviceStatus: params.deviceStatus,
        userId: params.userId || null,
        agentId: params.agentId || null,
      })
    );
  }

  // 发送MQTT消息 { ms: number }
  @Post('/sendMs')
  async sendMs(@Body() params: { deviceNo: string; ms: number }) {
    return this.ok(await this.deviceDeviceService.sendMs(params));
  }
}
